package com.tanhua.server.service;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.server.mapper.UserMapper;
import com.tanhua.server.pojo.Comments;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class CommentsService {
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public PageResult queryCommentsList(String publishId, Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setCounts(0);
        pageResult.setPages(0);
        List<Comment> commentList = quanZiApi.queryCommentList(publishId, page, pageSize);
        //如果评论列表为空,直接返回
        if (CollectionUtils.isEmpty(commentList))
            return pageResult;
        //评论的用户id的集合
        Set<Long> userIds = commentList.stream().map(Comment::getUserId).collect(Collectors.toSet());
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(UserInfo::getUserId,userIds);
        //获取评论用户的信息
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(wrapper);
        //封装Comments
        ArrayList<Comments> commentsList = new ArrayList<>();
        for (Comment comment : commentList) {
            for (UserInfo userInfo : userInfoList) {
                if (comment.getUserId().longValue() == userInfo.getUserId()){
                    Comments comments = new Comments();
                    comments.setId(comment.getId().toHexString());
                    comments.setAvatar(userInfo.getLogo());
                    comments.setNickname(userInfo.getNickName());
                    comments.setContent(comment.getContent());
                    comments.setCreateDate(new DateTime(comment.getCreated()).toString("yyyy年MM月dd日 HH:mm"));
                    String likeUserCommentKey = "QUANZI_COMMENT_LIKE_" + user.getId() + "_" + comments.getId();
                    comments.setHasLiked(this.redisTemplate.hasKey(likeUserCommentKey) ? 1 : 0); //是否点赞

                    String likeCommentKey = "QUANZI_COMMENT_LIKE_" + comments.getId();
                    String value = this.redisTemplate.opsForValue().get(likeCommentKey);
                    if(StringUtils.isNotEmpty(value)){
                        comments.setLikeCount(Integer.valueOf(value)); //点赞数
                    }else{
                        comments.setLikeCount(0); //点赞数
                    }
                    commentsList.add(comments);
                    break;
                }
            }
        }
        pageResult.setItems(commentsList);
        return pageResult;
    }

    //保存评论

    @Autowired
    private UserMapper userMapper;
    public Boolean saveComments(String publishId, String content) {

        Long userId = UserThreadLocal.get().getId();
        //todo 校验是否为冻结发言
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",userId);
        User user1= userMapper.selectOne(queryWrapper);
        //判断用户冻结状态
        if (user1.getFreezingRange()==2){
            String redisUserKey="FREEZEUPDATE"+userId;
            //判断redis缓存是否存在 不存在修改用户状态为正常
            if (!redisTemplate.hasKey(redisUserKey)){
                UpdateWrapper<User> updateWrapper=new UpdateWrapper<>();
                updateWrapper.set("freezingRange",0).set("freezingTime",0).eq("id",user1.getId());
                userMapper.update(user1,updateWrapper);
            }else {
                System.out.println(redisTemplate.getExpire(redisUserKey));
                return null;
            }
        }

        boolean flag = quanZiApi.saveComment(userId, publishId, 2, content);
        if (!flag)
            return null;
        //缓存中保存评论数
        String commentsKey = "QUANZI_COMMENT_CONTENT_" + publishId;
        //判断缓存中是否存有喜欢数
        Long count = null;
        if (!redisTemplate.hasKey(commentsKey)) {
            //没有,查询获得,并放入缓存中
            count = quanZiApi.queryCommentCount(publishId, 2);
            redisTemplate.opsForValue().set(commentsKey, count.toString());
        }else{
            count = redisTemplate.opsForValue().increment(commentsKey);
        }
        return true;
    }
}
